<template>

<div>

  <a-dropdown>
    <div class="header-avatar" style="cursor: pointer">
      <a-avatar class="avatar" size="small" shape="circle" :src="user.avatar" />
      <span class="name">{{ user.name ? user.name : user.loginName }}</span>
    </div>
    <a-menu :class="['avatar-menu']" slot="overlay">
      <a-menu-item @click="changePassword">
        <a-icon type="setting" />
        <span>修改密码</span>
      </a-menu-item>
      <a-menu-divider />
      <a-menu-item @click="changePhone">
        <a-icon type="setting" />
        <span>修改手机号</span>
      </a-menu-item>
      <a-menu-divider />
      <a-menu-item @click="logout">
        <a-icon style="margin-right: 8px" type="poweroff" />
        <span>退出登录</span>
      </a-menu-item>
    </a-menu>
  </a-dropdown>
  <!-- 修改密码对话框 -->
  <a-modal
    title="修改密码"
    :visible="visible"
    @ok="updatePasswordOK"
    @cancel="visible=false"
  >
    <a-form-model
      ref="updatePasswordRef"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
      style="margin: 0 auto;"
      :model="updateFormData"
      :rules="updateFormRules"
    >
      <a-form-model-item label="旧密码" prop="oldPassword">
        <a-input
          size="large"
          placeholder="请输入旧密码"
          v-model="updateFormData.oldPassword"
        ><a-icon slot="prefix" type="key" /></a-input>
      </a-form-model-item>
      <a-form-model-item label="新密码" prop="password">
        <a-input
          size="large"
          placeholder="请设置6-20位登录密码"
          v-model="updateFormData.password"
        ><a-icon slot="prefix" type="key" /></a-input>
      </a-form-model-item>
      <a-form-model-item label="确认新密码" prop="confirmPassword">
        <a-input
          size="large"
          placeholder="请再次输入新的登录密码"
          v-model="updateFormData.confirmPassword"
        ><a-icon slot="prefix" type="key" /></a-input>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
  <!-- 修改手机号对话框 -->
  <a-modal
    title="修改手机号"
    :visible="visible1"
    @ok="updatePhoneOK"
    @cancel="visible1=false"
  >
    <a-form-model
      ref="updatePhoneRef"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
      style="margin: 0 auto;"
      :model="updatePhoneData"
      :rules="phoneFormRules"
    >
      <a-form-model-item label="手机号" prop="phoneNumber">
        <a-input
          size="large"
          placeholder="请输入手机号"
          v-model="updatePhoneData.phoneNumber"
        ><a-icon slot="prefix" type="key" /></a-input>
      </a-form-model-item>
      <a-form-model-item label="验证码" prop="verificationCode">
        <a-input
          size="large"
          placeholder="请输入短信验证码"
          v-model="updatePhoneData.verificationCode"
        ><a-icon slot="prefix" type="key" /></a-input>
          <a-button
                :disabled="disabled"
                @click="sendCode"
                class="sendYZMbtn"
                >{{ text }}</a-button
              >
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</div>
</template>

<script>
import { mapGetters } from "vuex";
import { loginOut,loginUserUpdatePassword,amendPhoneYZM,confirmChangeMobile } from "@/services/user";
import { removeAuthorization } from '@/utils/request'
import {AUTH_TYPE} from "../../utils/request";
export default {
  data() {
    //自定义校验规则,验证确认密码和设置密码是否相同
    let checkPasswordValid = (rule, value, callback) => {
      if (value !== this.updateFormData.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    let checkMobilePhone = (rule, value, callback) => {
      var reg =
        /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
      if (reg.test(value)) {
        // 如果合法,然后发送请求校验唯一
        this.phoneRegistered = true;
            callback();
      } else {
        // 如果不合法,提示输入正确的手机号
        this.phoneRegistered = false;
        callback(new Error("请输入正确的手机号"));
      }
    };
    return {
      // 修改密码对话框校验规则
      text: "获取验证码",
      phoneFormRules:{
        phoneNumber: [
            { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobilePhone, trigger: "blur" },
        ],
        verificationCode: [
            { required: true, message: "验证码", trigger: "blur" }
        ],
      },
      updateFormRules:{
        oldPassword: [
            { required: true, message: "密码不能为空", trigger: "blur" },
            { min: 6, max: 20, message: "密码长度为6-20位", trigger: "blur" },
        ],
        password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
            { min: 6, max: 20, message: "密码长度为6-20位", trigger: "blur" },
        ],
        confirmPassword: [
            { required: true, message: "请再次输入密码", trigger: "blur" },
            { validator: checkPasswordValid, trigger: "blur" },
          ],

      },
      //修改手机号
      updatePhoneData:{
        phoneNumber:'',
        verificationCode:''
      },
      // 修改密码对话框数据
      updateFormData:{
        oldPassword:"",
        password:"",
        confirmPassword:""
      },
      visible1:false,
      visible: false,
      menuObj:{},
      confirmLoading:false,
      phoneRegistered:false,
      disabled:false,
       rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
    }

    };
  },
  name: "HeaderAvatar",
  computed: {
    ...mapGetters("account", ["user"]),
  },
  methods: {
     // 点击按钮发送手机验证码
    sendCode() {
      var reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (reg.test(this.updatePhoneData.phoneNumber) && this.phoneRegistered) {
        // 手机号合法,准备发送获取验证码
        amendPhoneYZM({
          phoneNumber: this.updatePhoneData.phoneNumber,
        })
          .then((res) => {
            if (res.data.status == 0) {
              let n = 60;
                this.disabled = true;
                const int = setInterval(() => {
                  this.text = n + "秒后重新发送";
                  n--;
                  if (n === 0) {
                    this.disabled = false;
                    this.text = "获取验证码";
                    clearInterval(int);
                  }
                }, 1000);
              // this.$message.success("验证码发送成功");
            } else {
              // this.$message.error("验证码发送失败");
            }
          })
          .catch((err) => {
            console.log(err);
          });
        
      }
    },
    updatePhoneOK(){
        this.$refs.updatePhoneRef.validate(valid => {
        if(valid){
          // 发送请求
          const params = {
        phoneNumber: this.updatePhoneData.phoneNumber,
        verifyCode: this.updatePhoneData.verificationCode
      }
          confirmChangeMobile(params).then(res => {
            if(res.data.status == 0){
              this.$message.success('修改手机号成功,请重新登录');
              this.visible1 = false
              setTimeout(() => {
                this.logout()
              }, 1000);
            } else {
              this.$message.error('修改手机号失败,请重试');
            }
          })
        } else {
          return false
        }
      })
    },
    // 修改密码对话框 确认按钮
    updatePasswordOK(){
      this.$refs.updatePasswordRef.validate(valid => {
        if(valid){
          // 发送请求
          loginUserUpdatePassword(this.updateFormData).then(res => {
            if(res.data.status == 0){
              this.$message.success('修改密码成功,请重新登录');
              this.visible = false
              setTimeout(() => {
                this.logout()
              }, 1000);
            } else {
              this.$message.error('修改密码失败,请重试');
            }
          })
        } else {
          return false
        }
      })
    },
    //退出登录
    logout() {
      // 服务器端退出登录
      loginOut().then((res) => {
        console.log(res);
        this.$router.push("/login");
        // 清除本地存储
        window.localStorage.clear();
        window.sessionStorage.clear();
        removeAuthorization(AUTH_TYPE.BASIC)
      });
    },
    //修改密码
    changePassword() {
      this.visible = true
    },
    changePhone(){
      this.visible1 = true
    }
  },
};
</script>

<style lang="less">
.header-avatar {
  display: inline-flex;
  .avatar,
  .name {
    align-self: center;
  }
  .avatar {
    margin-right: 8px;
  }
  .name {
    font-weight: 500;
  }
}
.avatar-menu {
  width: 150px;
}
.sendYZMbtn {
  color: #6bb8ff;
  outline: none;
  border: none;
  box-shadow: none;
  font-size: 13px;
  float: right;
  margin: -37px 8px 0 0 ;
  padding: 0;
}
</style>
